<template>
    <Dialog :app-dialog="appDialog">
        <el-form ref="setFormRef" class="setForm" :model="setForm" :rules="rules" label-width="80px">
            <el-form-item
                v-for="item in attrList"
                :key="item"
                :label="item.name"
                :prop="item.system_code"
                :class="{ blank: !item.name }">
                <el-input v-if="item.system_code === 'name'" v-model="setForm.name" placeholder="请输入收件人" />
                <el-input
                    v-if="item.system_code === 'mobile'"
                    v-model="setForm.mobile"
                    placeholder="请输入收件人电话"
                    @input="v => (setForm.mobile = v.replace(/[^\d]/g, ''))" />
                <template v-if="item.system_code === 'region'">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="setForm.region"
                        class="address"
                        :options="city"
                        :props="defaultProps"
                        placeholder="请选择省市区"
                        @change="orgChange" />
                    <el-input v-model="setForm.address" class="minute" placeholder="请输入详细地址" />
                </template>
            </el-form-item>
        </el-form>
    </Dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';

import Dialog from '@/components/Dialog.vue';
import city from '@/assets/js/city.js';
import { validatePhone } from '@/utils/validate';

import { getAttrList, editAddress } from '@/api/smartMarketing/fissionDrainage';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['refresh']);
const route = useRoute();
const setFormRef = ref(null);
const cascaderRef: any = ref(null);
const { id: activity_id } = route.query;
const rowData = ref<any>(null); // 点击列表的数据
// 获取属性列表
const attrList = ref<any>([]);
// 选择区域配置
const defaultProps = ref({
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'code'
});
// 修改参数
const setForm = ref({
    name: '', // 姓名
    mobile: '', // 手机号
    region: '', // 地址
    address: '' // 详细地址
});
// 手机验证
const phoneVerify = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('请输入收件人手机号'));
    else if (validatePhone(value)) {
        callback(new Error('手机格式有误'));
    } else {
        callback();
    }
};

// 校验规则
const rules = reactive({
    name: [{ required: true, message: '请输入收件人', trigger: ['blur', 'change'] }],
    mobile: [{ required: true, validator: phoneVerify, trigger: ['blur', 'change'] }],
    region: [{ required: true, message: '请选择省市区', trigger: ['blur', 'change'] }]
});

// 获取修改属性
const initAttrList = (activity_record_id: any) => {
    const params = {
        activity_id,
        activity_record_id
    };
    getAttrList(params).then((res: any) => {
        const index = res.findIndex((item: any) => item.system_code === 'address');
        res[index].name = '';
        attrList.value = res;
    });
};

// 获取区域code
const getCode = (data: any) => {
    const res = (data.area && data.area.code) || (data.city && data.city.code) || (data.province && data.province.code);
    return res;
};

// 打开弹框
const open = (row: any) => {
    const { consignee_name, consignee_phone, consignee_region, consignee_address } = row;
    rowData.value = row;
    setForm.value.name = consignee_name;
    setForm.value.mobile = consignee_phone;
    setForm.value.region = getCode(consignee_region);
    setForm.value.address = consignee_address;
    initAttrList(row.id);
    appDialog.visible = true;
};

// 弹框取消
const cancelHandel = () => {
    if (!setFormRef.value) return;
    setForm.value.address = '';
    setFormRef.value.resetFields();
    appDialog.visible = false;
};
// 弹框确定
const submitHandel = async () => {
    if (!setFormRef.value) return;
    await setFormRef.value.validate((valid, fields) => {
        if (valid && setForm.value.address !== '') {
            const { activity_record_id, external_userid: external_user_id, reward_id } = rowData.value;
            const params = {
                ...setForm.value,
                activity_id,
                activity_record_id,
                external_user_id,
                reward_id
            };
            editAddress(params).then(() => {
                ElMessage.success('修改成功');
                emit('refresh');
                cancelHandel();
            });
        } else {
            ElMessage.error('请输入详细地址');
        }
    });
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value[0].togglePopperVisible();
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '修改地址',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});

defineExpose({
    open
});
onMounted(() => {});
</script>

<style lang="scss" scoped>
.setForm {
    :deep(.address) {
        width: 100%;
    }
    .minute {
        margin-top: 16px;
    }
    .blank {
        display: none;
    }
}
</style>
